package com.hmdp.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private ISeckillVoucherService seckillVoucherService;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public Result<String> seckillVoucher(Long voucherId) {
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
        if (seckillVoucher == null) {
            Result.fail("代金券不存在");
        }
        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
            Result.fail("秒杀尚未开始");
        }
        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
            Result.fail("秒杀已经结束");
        }
        if (seckillVoucher.getStock() <= 0) {
            Result.fail("代金券库存不足");
        }
        boolean success = seckillVoucherService.update()
                .setSql("stock=stock-1")
                .gt("stock", 0)
                .eq("voucher_id", voucherId)
                .update();
        if (!success) {
            Result.fail("代金券库存不足");
        }
        Long user_id = UserHolder.getUser().getId();
        //悲观锁
//        synchronized (user_id.toString().intern()) {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            return proxy.createOrder(voucherId);
//        }
        //分布式锁
        RLock lock = redissonClient.getLock("lock:voucher" + user_id);
        boolean isLock = false;
        try {
            isLock = lock.tryLock(1, 10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (!isLock) {
            Result.fail("不允许重复下单");
        }
        try {
            return getService().createOrder(voucherId);
        } finally {
            lock.unlock();
        }
    }
    //解决事务失效
    private VoucherOrderServiceImpl getService(){
        return SpringUtil.getBean(this.getClass());   //SpringUtil工具类见下面代码
    }

    @Transactional
    public Result<String> createOrder(Long voucherId) {
        Integer count = super.query().eq("user_id", UserHolder.getUser().getId()).eq("voucher_id", voucherId).count();
        if (count > 0) {
            Result.fail("你已经购买过啦");
        }
        VoucherOrder voucherOrder = new VoucherOrder();
        String orderId = UUID.randomUUID().toString();
        voucherOrder.setId(Long.valueOf(orderId));
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        super.save(voucherOrder);
        return Result.ok(orderId);
    }
}
